﻿using System;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using RFIDCard_747;
using Advantech.Adam;
using System.Threading;
using GatewayInspect.Common;
using System.Data;

namespace GatewayInspect
{
    public class RFIDReader_747
    {
        #region 读卡器变量

        private Reader Reader = new Reader();

        private string TID_Length = "6";
        private int res, resJ, resC, EPC_Word, m_hSocket = -1, m_hSocketJ = -1, m_hSocketC = -1, OK = 0;
        private int nCurrnetAnt = 1;
        private int isClosed = 1;//闸机是否完全闭合
        private byte connect_OK = 0;
        private string deviceType = "2";//设备的类型 1:一个读卡器一个天线 2:一个读卡器两个天线
        private byte[] mask = new byte[96];
        private byte[] DB = new byte[128];
        private byte[] IDBuffer = new byte[7680];
        private byte[] IDTemp = new byte[120];
        private byte[] AccessPassWord = new byte[4];
        private byte[,] TagBuffer = new byte[100, 130];

        private string readerip;
        private uint readerport;
        private string hostip;
        private uint hostport;

        private string readeripJ;
        private uint readerportJ;
        private string hostipJ;
        private uint hostportJ;

        private string readeripC;
        private uint readerportC;
        private string hostipC;
        private uint hostportC;

        #endregion

        #region 6052变量

        private AdamSocket adamModbus;
        private Adam6000Type m_Adam6000Type;
        private string m_szIP;
        private int m_iPort;
        private int m_iDiTotal;

        private int m_UpPort = 1;//起杆IO号
        private int m_StartIndex = 1;

        private AdamSocket adamModbusJ;
        private Adam6000Type m_Adam6000TypeJ;
        private string m_szIPJ;
        private int m_iPortJ;
        private int m_iDiTotalJ;

        private int m_UpPortJ = 1;//起杆IO号
        private int m_StartIndexJ = 1;

        private AdamSocket adamModbusC;
        private Adam6000Type m_Adam6000TypeC;
        private string m_szIPC;
        private int m_iPortC;
        private int m_iDiTotalC;

        private int m_UpPortC = 1;//起杆IO号
        private int m_StartIndexC = 1;

        #endregion

        private System.Timers.Timer _timer;
        private int _interval = 500;
        private bool _isReading = false;
        private object _timerLock = new object();

        public int InAnt { get; set; }//进门天线号
        public int OutAnt { get; set; }//出门天线号

        #region 定义事件
        public delegate void ShowMsgHandler(string sMsg);
        public event ShowMsgHandler OnShowMsg;//显示提示信息

        public delegate void AfterReadCardInfoHandler(string strTid, string strEPC, int iAnt);
        public event AfterReadCardInfoHandler OnAfterReadCardInfo;
        //闸机是否闭合
        public delegate void IfCloseHandler(string state);
        public event IfCloseHandler IfCloseZhaji;

        public delegate void AfterUpBarrierHandler();
        public event AfterUpBarrierHandler OnAfterUpBarrier;

        public delegate void ChangeCtrlEnableHandle(string state);
        public event ChangeCtrlEnableHandle OnChangeCtrlEnable;//按钮控件使能控制
        #endregion

        #region Singleton

        private static RFIDReader_747 _instance;
        private static object _lock = new object();

        private RFIDReader_747()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            try
            {
                deviceType = ConfigurationManager.AppSettings["DeviceType"];
                if (deviceType == "2" || deviceType == "3")
                {
                    //初始化读卡器
                    hostip = config.AppSettings.Settings["HostIP"].Value;//GetHostIP();
                    hostport = Convert.ToUInt16(config.AppSettings.Settings["HostPort"].Value);
                    readerip = config.AppSettings.Settings["AntReaderIP"].Value;
                    readerport = Convert.ToUInt16(config.AppSettings.Settings["AntReaderPort"].Value);
                    _interval = Convert.ToInt32(config.AppSettings.Settings["AntReaderInterval"].Value);
                    //初始化6052
                    m_szIP = System.Configuration.ConfigurationManager.AppSettings["AdamIP"];
                    m_iPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["AadmPort"]);//502
                    m_UpPort = Convert.ToInt32(ConfigurationManager.AppSettings["UpPort"]);//起杆IO号
                    m_StartIndex = Convert.ToInt32(ConfigurationManager.AppSettings["StartIndex"]);
                    adamModbus = new AdamSocket();
                    adamModbus.SetTimeout(1000, 1000, 1000); // set timeout for TCP
                    m_Adam6000Type = Adam6000Type.Adam6052; // the sample is for ADAM-6050
                    m_iDiTotal = DigitalInput.GetChannelTotal(m_Adam6000Type);
                }else{
                    //初始化读卡器
                    hostipJ = config.AppSettings.Settings["HostIPJ"].Value;//GetHostIP();
                    hostportJ = Convert.ToUInt16(config.AppSettings.Settings["HostPortJ"].Value);
                    readeripJ = config.AppSettings.Settings["AntReaderIPJ"].Value;
                    readerportJ = Convert.ToUInt16(config.AppSettings.Settings["AntReaderPortJ"].Value);

                    hostipC = config.AppSettings.Settings["HostIPC"].Value;//GetHostIP();
                    hostportC = Convert.ToUInt16(config.AppSettings.Settings["HostPortC"].Value);
                    readeripC = config.AppSettings.Settings["AntReaderIPC"].Value;
                    readerportC = Convert.ToUInt16(config.AppSettings.Settings["AntReaderPortC"].Value);

                    _interval = Convert.ToInt32(config.AppSettings.Settings["AntReaderIntervalJ"].Value);
                    //初始化6052
                    m_szIPJ = System.Configuration.ConfigurationManager.AppSettings["AdamIPJ"];
                    m_iPortJ = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["AadmPortJ"]);//502
                    m_UpPortJ = Convert.ToInt32(ConfigurationManager.AppSettings["UpPortJ"]);//起杆IO号
                    m_StartIndexJ = Convert.ToInt32(ConfigurationManager.AppSettings["StartIndexJ"]);
                    adamModbusJ = new AdamSocket();
                    adamModbusJ.SetTimeout(1000, 1000, 1000); // set timeout for TCP
                    m_Adam6000TypeJ = Adam6000Type.Adam6052; // the sample is for ADAM-6050
                    m_iDiTotalJ = DigitalInput.GetChannelTotal(m_Adam6000TypeJ);

                    m_szIPC = System.Configuration.ConfigurationManager.AppSettings["AdamIPC"];
                    m_iPortC = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["AadmPortC"]);//502
                    m_UpPortC = Convert.ToInt32(ConfigurationManager.AppSettings["UpPortC"]);//起杆IO号
                    m_StartIndexC = Convert.ToInt32(ConfigurationManager.AppSettings["StartIndexC"]);
                    adamModbusC = new AdamSocket();
                    adamModbusC.SetTimeout(1000, 1000, 1000); // set timeout for TCP
                    m_Adam6000TypeC = Adam6000Type.Adam6052; // the sample is for ADAM-6050
                    m_iDiTotalC = DigitalInput.GetChannelTotal(m_Adam6000TypeC);


                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public static RFIDReader_747 GetInstance()
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new RFIDReader_747();
                    }
                }
            }
            return _instance;
        }

        #endregion

        public bool IsConnect
        {
            get
            {
                return connect_OK == 1 && (m_hSocket > 0 || m_hSocketJ > 0 || m_hSocketC>0);
            }
        }
        public bool IsConnectJ
        {
            get
            {
                return connect_OK == 1 && m_hSocketJ > 0;
            }
        }
        public bool IsConnectC
        {
            get
            {
                return connect_OK == 1 && m_hSocketC > 0;
            }
        }

        /// <summary>
        /// 连接读写器和6052模块
        /// </summary>
        public void Connect()
        {
            if (deviceType == "2"||deviceType=="3")
            {
                connect_OK = 0;//0--no connect, 1--connected
                for (int i = 0; i < 3; i++)//连接读卡器
                {
                    res = Reader.Net_ConnectScanner(ref m_hSocket, readerip, readerport, hostip, hostport);
                    if (res == OK)
                        break;
                }
                if ((res != OK))
                {
                    MessageBox.Show("读卡器连接失败！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                //连接6052
                if (!adamModbus.Connect(m_szIP, ProtocolType.Tcp, m_iPort))
                {
                    MessageBox.Show("连接6052模块失败！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                connect_OK = 1;//0--no connect, 1--connected
                changeCtrlEnable("conn");
                ShowMsg("读卡器已连接...");
            }
            else
            {
                connect_OK = 0;//0--no connect, 1--connected
                for (int i = 0; i < 3; i++)//连接进门读卡器
                {
                    resJ = Reader.Net_ConnectScanner(ref m_hSocketJ, readeripJ, readerportJ, hostipJ, hostportJ);
                    if (resJ == OK)
                        break;
                }
                if ((resJ != OK))
                {
                    MessageBox.Show("进门读卡器连接失败！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                for (int i = 0; i < 3; i++)//连接出门读卡器
                {
                    resC = Reader.Net_ConnectScanner(ref m_hSocketC, readeripC, readerportC, hostipC, hostportC);
                    if (resC == OK)
                        break;
                }
                if ((resC != OK))
                {
                    MessageBox.Show("出门读卡器连接失败！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                //连接进门6052
                if (!adamModbusJ.Connect(m_szIPJ, ProtocolType.Tcp, m_iPortJ))
                {
                    MessageBox.Show("连接进门6052模块失败！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                //连接出门6052
                if (!adamModbusC.Connect(m_szIPC, ProtocolType.Tcp, m_iPortC))
                {
                    MessageBox.Show("连接进门6052模块失败！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                connect_OK = 1;//0--no connect, 1--connected
                changeCtrlEnable("conn");
                ShowMsg("读卡器已连接...");
                
            }


            
        }

        /// <summary>
        /// 断开读写器连接和6052
        /// </summary>
        public void Disconnect()
        {
            EndRead();
            //断开连接设备功能
            if (connect_OK == 0)
                return;

            if (deviceType == "2" || deviceType == "3")
            {
                res = Reader.Net_DisconnectScanner(m_hSocket);
                if (res != OK)
                {
                    ShowMsg("断开读卡器失败！");
                    MessageBox.Show("断开读卡器失败！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                //断开6052
                adamModbus.Disconnect(); // disconnect slave

                m_hSocket = -1;
                connect_OK = 0;
                changeCtrlEnable("disconn");
                ShowMsg("读卡器已断开...");
            }
            else
            {
                resJ = Reader.Net_DisconnectScanner(m_hSocketJ);
                if (resJ != OK)
                {
                    ShowMsg("断开进门读卡器失败！");
                    MessageBox.Show("断开进门读卡器失败！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                resC = Reader.Net_DisconnectScanner(m_hSocketC);
                if (resC != OK)
                {
                    ShowMsg("断开出门读卡器失败！");
                    MessageBox.Show("断开出门读卡器失败！", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                //断开6052
                adamModbusJ.Disconnect(); // disconnect slave
                //断开6052
                adamModbusC.Disconnect(); // disconnect slave
                m_hSocketJ = -1;
                m_hSocketC = -1;
                connect_OK = 0;
                changeCtrlEnable("disconn");
                ShowMsg("读卡器已断开...");

            }
        }

        /// <summary>
        /// 开始读卡
        /// </summary>
        public void BeginRead()
        {
            if (IsConnect)
            {
                if (_timer == null)
                {
                    _timer = new System.Timers.Timer();
                    _timer.Interval = _interval;
                    _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
                }
                if (!_timer.Enabled)
                {
                    _timer.Enabled = true;
                    changeCtrlEnable("scan");
                    ShowMsg("正在读卡...");
                }
            }
        }

        /// <summary>
        /// 停止读卡
        /// </summary>
        public void EndRead()
        {
            if (_timer != null && _timer.Enabled)
            {
                _timer.Enabled = false;
                changeCtrlEnable("conn");
                ShowMsg("停止读卡...");
            }
        }
        
        //起杆
        public void UpBarrier()
        {
            if (deviceType == "2" || deviceType == "3")
            {
                try
                {
                    int iStart = 17 + m_UpPort;//m_UpPort表示IO输出端口号
                    if (adamModbus.Modbus().ForceSingleCoil(iStart, 1))
                    {
                        Thread.Sleep(200);//0.2秒后发送低电平
                        adamModbus.Modbus().ForceSingleCoil(iStart, 0);
                    }
                    else//发送失败，则断开，重新连接，再尝试一次
                    {
                        TryReUpBarrier();
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(typeof(RFIDReader_747), ex);
                    TryReUpBarrier();
                }

            }
            else
            {
                if (nCurrnetAnt==InAnt)
                {
                    try
                    {
                        int iStart = 17 + m_UpPortJ;//m_UpPort表示IO输出端口号
                        if (adamModbusJ.Modbus().ForceSingleCoil(iStart, 1))
                        {
                            Thread.Sleep(200);//0.2秒后发送低电平
                            adamModbusJ.Modbus().ForceSingleCoil(iStart, 0);
                        }
                        else//发送失败，则断开，重新连接，再尝试一次
                        {
                            TryReUpBarrierJ();
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog(typeof(RFIDReader_747), ex);
                        TryReUpBarrierJ();
                    }
                }
                else
                {
                    try
                    {
                        int iStart = 17 + m_UpPortC;//m_UpPort表示IO输出端口号
                        if (adamModbusC.Modbus().ForceSingleCoil(iStart, 1))
                        {
                            Thread.Sleep(200);//0.2秒后发送低电平
                            adamModbusC.Modbus().ForceSingleCoil(iStart, 0);
                        }
                        else//发送失败，则断开，重新连接，再尝试一次
                        {
                            TryReUpBarrierC();
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog(typeof(RFIDReader_747), ex);
                        TryReUpBarrierC();
                    }
                    
                }
                
            }
            
        }

        private void TryReUpBarrier()
        {
            LogHelper.WriteLog(typeof(RFIDReader_747), "发送起杆指令失败");
            adamModbus.Disconnect();
            LogHelper.WriteLog(typeof(RFIDReader_747), "断开连接");
            adamModbus.Connect(m_szIP, ProtocolType.Tcp, m_iPort);
            LogHelper.WriteLog(typeof(RFIDReader_747), "重新建立连接");
            int iStart = 17 + m_UpPort;//m_UpPort表示IO输出端口号
            if (adamModbus.Modbus().ForceSingleCoil(iStart, 1))
            {
                Thread.Sleep(200);//0.2秒后发送低电平
                adamModbus.Modbus().ForceSingleCoil(iStart, 0);
                LogHelper.WriteLog(typeof(RFIDReader_747), "重新发送起杆指令");
            }
        }
        private void TryReUpBarrierJ()
        {
            LogHelper.WriteLog(typeof(RFIDReader_747), "发送起杆指令失败");
            adamModbusJ.Disconnect();
            LogHelper.WriteLog(typeof(RFIDReader_747), "断开连接");
            adamModbusJ.Connect(m_szIPJ, ProtocolType.Tcp, m_iPortJ);
            LogHelper.WriteLog(typeof(RFIDReader_747), "重新建立连接");
            int iStart = 17 + m_UpPortJ;//m_UpPort表示IO输出端口号
            if (adamModbusJ.Modbus().ForceSingleCoil(iStart, 1))
            {
                Thread.Sleep(200);//0.2秒后发送低电平
                adamModbusJ.Modbus().ForceSingleCoil(iStart, 0);
                LogHelper.WriteLog(typeof(RFIDReader_747), "重新发送起杆指令");
            }
        }
        private void TryReUpBarrierC()
        {
            LogHelper.WriteLog(typeof(RFIDReader_747), "发送起杆指令失败");
            adamModbusC.Disconnect();
            LogHelper.WriteLog(typeof(RFIDReader_747), "断开连接");
            adamModbusC.Connect(m_szIPC, ProtocolType.Tcp, m_iPortC);
            LogHelper.WriteLog(typeof(RFIDReader_747), "重新建立连接");
            int iStart = 17 + m_UpPortC;//m_UpPort表示IO输出端口号
            if (adamModbusC.Modbus().ForceSingleCoil(iStart, 1))
            {
                Thread.Sleep(200);//0.2秒后发送低电平
                adamModbusC.Modbus().ForceSingleCoil(iStart, 0);
                LogHelper.WriteLog(typeof(RFIDReader_747), "重新发送起杆指令");
            }
        }

        /// <summary>
        /// 起降杆是否是闭合状态
        /// </summary>
        /// <param name="di">连接到了6052的1号口</param>
        /// <returns></returns>
        public bool IsBarrierClosed(int di = 1)
        {
            try
            {
                bool[] bDatatemp;
                if (adamModbus.Modbus().ReadCoilStatus(m_StartIndex, m_iDiTotal, out bDatatemp))
                {
                    return bDatatemp[di];
                }
                else//读取失败，则断开重新连接，再读取一次
                {
                    return TryReReadCoilStatus(di);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(RFIDReader_747), ex);
                return TryReReadCoilStatus(di);
            }
        }
        /// <summary>
        /// 起降杆是否是闭合状态(进门)
        /// </summary>
        /// <param name="di">连接到了6052的1号口</param>
        /// <returns></returns>
        public bool IsBarrierClosedJ(int di = 1)
        {
            try
            {
                bool[] bDatatemp;
                if (adamModbusJ.Modbus().ReadCoilStatus(m_StartIndexJ, m_iDiTotalJ, out bDatatemp))
                {
                    return bDatatemp[di];
                }
                else//读取失败，则断开重新连接，再读取一次
                {
                    return TryReReadCoilStatusJ(di);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(RFIDReader_747), ex);
                return TryReReadCoilStatusJ(di);
            }
        }
        /// <summary>
        /// 起降杆是否是闭合状态(出门)
        /// </summary>
        /// <param name="di">连接到了6052的1号口</param>
        /// <returns></returns>
        public bool IsBarrierClosedC(int di = 1)
        {
            try
            {
                bool[] bDatatemp;
                if (adamModbusC.Modbus().ReadCoilStatus(m_StartIndexC, m_iDiTotalC, out bDatatemp))
                {
                    return bDatatemp[di];
                }
                else//读取失败，则断开重新连接，再读取一次
                {
                    return TryReReadCoilStatusC(di);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(RFIDReader_747), ex);
                return TryReReadCoilStatusC(di);
            }
        }
        private bool TryReReadCoilStatus(int di)
        {
            LogHelper.WriteLog(typeof(RFIDReader_747), "读取闸机状态失败");
            adamModbus.Disconnect();
            LogHelper.WriteLog(typeof(RFIDReader_747), "断开连接");
            adamModbus.Connect(m_szIP, ProtocolType.Tcp, m_iPort);
            LogHelper.WriteLog(typeof(RFIDReader_747), "重新建立连接");
            bool[] bDatatemp;
            if (adamModbus.Modbus().ReadCoilStatus(m_StartIndex, m_iDiTotal, out bDatatemp))
            {
                LogHelper.WriteLog(typeof(RFIDReader_747), "重新读取闸机状态");
                return bDatatemp[di];
            }
            return false;
        }
        private bool TryReReadCoilStatusJ(int di)
        {
            LogHelper.WriteLog(typeof(RFIDReader_747), "读取闸机状态失败");
            adamModbusJ.Disconnect();
            LogHelper.WriteLog(typeof(RFIDReader_747), "断开连接");
            adamModbusJ.Connect(m_szIPJ, ProtocolType.Tcp, m_iPortJ);
            LogHelper.WriteLog(typeof(RFIDReader_747), "重新建立连接");
            bool[] bDatatemp;
            if (adamModbusJ.Modbus().ReadCoilStatus(m_StartIndexJ, m_iDiTotalJ, out bDatatemp))
            {
                LogHelper.WriteLog(typeof(RFIDReader_747), "重新读取闸机状态");
                return bDatatemp[di];
            }
            return false;
        }
        private bool TryReReadCoilStatusC(int di)
        {
            LogHelper.WriteLog(typeof(RFIDReader_747), "读取闸机状态失败");
            adamModbusC.Disconnect();
            LogHelper.WriteLog(typeof(RFIDReader_747), "断开连接");
            adamModbusC.Connect(m_szIPC, ProtocolType.Tcp, m_iPortC);
            LogHelper.WriteLog(typeof(RFIDReader_747), "重新建立连接");
            bool[] bDatatemp;
            if (adamModbusC.Modbus().ReadCoilStatus(m_StartIndexC, m_iDiTotalC, out bDatatemp))
            {
                LogHelper.WriteLog(typeof(RFIDReader_747), "重新读取闸机状态");
                return bDatatemp[di];
            }
            return false;
        }

        /// <summary>
        /// 定时循环读卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (deviceType == "2")
            {
                if (!IsConnect || _isReading)
                    return;

                lock (_timerLock)
                {
                    int nCounter = 0, ID_len = 0, ID_len_temp = 0;
                    string strtemp, strEPC, strTID;
                    int mem = 1;//0-password, 1-EPC, 2-TID, 3-user,

                    _isReading = true;
                    try
                    {

                        if (!IsBarrierClosed())//如果是起杆状态，则不读卡
                        {
                            AfterUpBarrier();//起杆后清理一些读卡临时变量
                            IfCloseZhaji("0");
                            return;
                        }
                        IfCloseZhaji("1");
                        //设置天线
                        nCurrnetAnt = GetAntenna(nCurrnetAnt);
                        res = Reader.Net_SetAntenna(m_hSocket, nCurrnetAnt);
                        Array.Clear(TagBuffer, 0, TagBuffer.Length);
                        res = Reader.Net_EPC1G2_ReadLabelID(m_hSocket, mem, 0, 0, mask, IDBuffer, ref nCounter);
                        if (res == OK)
                        {
                            //MessageBox.Show("读卡成功");
                            //MessageBox.Show(nCounter.ToString());
                            for (int i = 0; i < nCounter; i++)
                            {
                                if (IDBuffer[ID_len] > 32)
                                {
                                    nCounter = 0;
                                    break;
                                }
                                ID_len_temp = IDBuffer[ID_len] * 2 + 1;
                                for (int j = 0; j < ID_len_temp; j++)
                                {
                                    TagBuffer[i, j] = IDBuffer[ID_len + j];
                                }
                                ID_len += ID_len_temp;
                            }
                            for (int i = 0; i < nCounter; i++)
                            {
                                mem = 2;//读TID
                                strtemp = "";
                                strEPC = "";
                                EPC_Word = TagBuffer[i, 0];
                                for (int j = 0; j < TagBuffer[i, 0] * 2; j++)
                                {
                                    strtemp = TagBuffer[i, j + 1].ToString("X2");
                                    strEPC += strtemp;
                                    IDTemp[j] = TagBuffer[i, j + 1];
                                }
                                Thread.Sleep(100);
                                res = Reader.Net_EPC1G2_ReadWordBlock(m_hSocket, Convert.ToByte(EPC_Word), IDTemp, Convert.ToByte(mem), Convert.ToByte(0), Convert.ToByte(TID_Length), DB, AccessPassWord);
                                //MessageBox.Show(strEPC);
                                //MessageBox.Show(res.ToString());
                                if (res == OK)
                                {
                                    strTID = "";
                                    for (i = 0; i < Convert.ToByte(TID_Length) * 2; i++)
                                    {
                                        strtemp = DB[i].ToString("X2");
                                        strTID += strtemp;
                                    }
                                    if (!string.IsNullOrEmpty(strTID) && OnAfterReadCardInfo != null)
                                    {
                                        //MessageBox.Show(strEPC+":  "+strTID);
                                        OnAfterReadCardInfo(strTID, strEPC, nCurrnetAnt);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog(typeof(RFIDReader_747), ex);
                    }
                    finally
                    {
                        _isReading = false;
                    }
                }
            }
            else if (deviceType == "3")
            {
                if (!IsConnect || _isReading)
                    return;

                lock (_timerLock)
                {
                    int nCounter = 0, ID_len = 0, ID_len_temp = 0;
                    string strtemp, strEPC, strTID;
                    int mem = 1;//0-password, 1-EPC, 2-TID, 3-user,

                    _isReading = true;
                    try
                    {
                        if (!IsBarrierClosed())//如果是起杆状态，则不读卡
                        {
                            AfterUpBarrier();//起杆后清理一些读卡临时变量
                            IfCloseZhaji("0");
                            return;
                        }
                        IfCloseZhaji("1");
                        res = Reader.Net_SetAntenna(m_hSocket, 1);
                        Array.Clear(TagBuffer, 0, TagBuffer.Length);
                        res = Reader.Net_EPC1G2_ReadLabelID(m_hSocket, mem, 0, 0, mask, IDBuffer, ref nCounter);
                        if (res == OK)
                        {
                            //MessageBox.Show("读卡成功");
                            //MessageBox.Show(nCounter.ToString());
                            for (int i = 0; i < nCounter; i++)
                            {
                                if (IDBuffer[ID_len] > 32)
                                {
                                    nCounter = 0;
                                    break;
                                }
                                ID_len_temp = IDBuffer[ID_len] * 2 + 1;
                                for (int j = 0; j < ID_len_temp; j++)
                                {
                                    TagBuffer[i, j] = IDBuffer[ID_len + j];
                                }
                                ID_len += ID_len_temp;
                            }
                            for (int i = 0; i < nCounter; i++)
                            {
                                mem = 2;//读TID
                                strtemp = "";
                                strEPC = "";
                                EPC_Word = TagBuffer[i, 0];
                                for (int j = 0; j < TagBuffer[i, 0] * 2; j++)
                                {
                                    strtemp = TagBuffer[i, j + 1].ToString("X2");
                                    strEPC += strtemp;
                                    IDTemp[j] = TagBuffer[i, j + 1];
                                }
                                Thread.Sleep(2000);
                                res = Reader.Net_EPC1G2_ReadWordBlock(m_hSocket, Convert.ToByte(EPC_Word), IDTemp, Convert.ToByte(mem), Convert.ToByte(0), Convert.ToByte(TID_Length), DB, AccessPassWord);
                                //MessageBox.Show(strEPC);
                                //MessageBox.Show(res.ToString());
                                if (res == OK)
                                {
                                    strTID = "";
                                    for (i = 0; i < Convert.ToByte(TID_Length) * 2; i++)
                                    {
                                        strtemp = DB[i].ToString("X2");
                                        strTID += strtemp;
                                    }
                                    if (!string.IsNullOrEmpty(strTID) && OnAfterReadCardInfo != null)
                                    {
                                        //MessageBox.Show(strEPC+":  "+strTID);
                                        string strCarNo = GetCarNo(strTID);
                                        string strSQL = "select RECTIME from IN_OUT_GATE where ORGCODE='" + Session.CurrentOrgCode + "' and CHEHAO='" + strCarNo + "' and IN_OUT_BS='1' order by RECTIME desc ";
                                        DataTable dtInOutGate = DataAccess.ExecuteDataTable(strSQL);//取最后一条进闸数据
                                        if (dtInOutGate != null && dtInOutGate.Rows.Count > 0)
                                        {
                                            nCurrnetAnt = OutAnt;
                                        }
                                        else
                                        {
                                            nCurrnetAnt = InAnt;
                                        }
                                        OnAfterReadCardInfo(strTID, strEPC, nCurrnetAnt);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog(typeof(RFIDReader_747), ex);
                    }
                    finally
                    {
                        _isReading = false;
                    }
                }
            
            }
            else
            {
                if (!IsConnect || _isReading)
                    return;

                lock (_timerLock)
                {
                    int nCounter = 0, ID_len = 0, ID_len_temp = 0;
                    string strtemp, strEPC, strTID;
                    int mem = 1;//0-password, 1-EPC, 2-TID, 3-user,

                    _isReading = true;
                    nCurrnetAnt = GetAntenna(nCurrnetAnt);
                    if (nCurrnetAnt==InAnt)
                    {
                        try
                        {
                            if (!IsBarrierClosedJ())//如果是起杆状态，则不读卡
                            {
                                AfterUpBarrier();//起杆后清理一些读卡临时变量
                                IfCloseZhaji("0");
                                return;
                            }
                            IfCloseZhaji("1");
                            //设置天线
                            //nCurrnetAnt = GetAntenna(nCurrnetAnt);
                            resJ = Reader.Net_SetAntenna(m_hSocketJ, nCurrnetAnt);
                            Array.Clear(TagBuffer, 0, TagBuffer.Length);
                            resJ = Reader.Net_EPC1G2_ReadLabelID(m_hSocketJ, mem, 0, 0, mask, IDBuffer, ref nCounter);
                            if (resJ == OK)
                            {
                                //MessageBox.Show("读卡成功");
                                //MessageBox.Show(nCounter.ToString());
                                for (int i = 0; i < nCounter; i++)
                                {
                                    if (IDBuffer[ID_len] > 32)
                                    {
                                        nCounter = 0;
                                        break;
                                    }
                                    ID_len_temp = IDBuffer[ID_len] * 2 + 1;
                                    for (int j = 0; j < ID_len_temp; j++)
                                    {
                                        TagBuffer[i, j] = IDBuffer[ID_len + j];
                                    }
                                    ID_len += ID_len_temp;
                                }
                                for (int i = 0; i < nCounter; i++)
                                {
                                    mem = 2;//读TID
                                    strtemp = "";
                                    strEPC = "";
                                    EPC_Word = TagBuffer[i, 0];
                                    for (int j = 0; j < TagBuffer[i, 0] * 2; j++)
                                    {
                                        strtemp = TagBuffer[i, j + 1].ToString("X2");
                                        strEPC += strtemp;
                                        IDTemp[j] = TagBuffer[i, j + 1];
                                    }
                                    Thread.Sleep(100);
                                    resJ = Reader.Net_EPC1G2_ReadWordBlock(m_hSocketJ, Convert.ToByte(EPC_Word), IDTemp, Convert.ToByte(mem), Convert.ToByte(0), Convert.ToByte(TID_Length), DB, AccessPassWord);
                                    //MessageBox.Show(strEPC);
                                    //MessageBox.Show(res.ToString());
                                    if (resJ == OK)
                                    {
                                        strTID = "";
                                        for (i = 0; i < Convert.ToByte(TID_Length) * 2; i++)
                                        {
                                            strtemp = DB[i].ToString("X2");
                                            strTID += strtemp;
                                        }
                                        if (!string.IsNullOrEmpty(strTID) && OnAfterReadCardInfo != null)
                                        {
                                            //MessageBox.Show(strEPC+":  "+strTID);
                                            OnAfterReadCardInfo(strTID, strEPC, nCurrnetAnt);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteLog(typeof(RFIDReader_747), ex);
                        }
                        finally
                        {
                            _isReading = false;
                        }
                    }
                    else
                    {
                        try
                        {
                            if (!IsBarrierClosedC())//如果是起杆状态，则不读卡
                            {
                                AfterUpBarrier();//起杆后清理一些读卡临时变量
                                IfCloseZhaji("0");
                                return;
                            }
                            IfCloseZhaji("1");
                            //设置天线
                            //nCurrnetAnt = GetAntenna(nCurrnetAnt);
                            resC = Reader.Net_SetAntenna(m_hSocketC, nCurrnetAnt);
                            Array.Clear(TagBuffer, 0, TagBuffer.Length);
                            resJ = Reader.Net_EPC1G2_ReadLabelID(m_hSocketC, mem, 0, 0, mask, IDBuffer, ref nCounter);
                            if (resC == OK)
                            {
                                //MessageBox.Show("读卡成功");
                                //MessageBox.Show(nCounter.ToString());
                                for (int i = 0; i < nCounter; i++)
                                {
                                    if (IDBuffer[ID_len] > 32)
                                    {
                                        nCounter = 0;
                                        break;
                                    }
                                    ID_len_temp = IDBuffer[ID_len] * 2 + 1;
                                    for (int j = 0; j < ID_len_temp; j++)
                                    {
                                        TagBuffer[i, j] = IDBuffer[ID_len + j];
                                    }
                                    ID_len += ID_len_temp;
                                }
                                for (int i = 0; i < nCounter; i++)
                                {
                                    mem = 2;//读TID
                                    strtemp = "";
                                    strEPC = "";
                                    EPC_Word = TagBuffer[i, 0];
                                    for (int j = 0; j < TagBuffer[i, 0] * 2; j++)
                                    {
                                        strtemp = TagBuffer[i, j + 1].ToString("X2");
                                        strEPC += strtemp;
                                        IDTemp[j] = TagBuffer[i, j + 1];
                                    }
                                    Thread.Sleep(100);
                                    resC = Reader.Net_EPC1G2_ReadWordBlock(m_hSocketC, Convert.ToByte(EPC_Word), IDTemp, Convert.ToByte(mem), Convert.ToByte(0), Convert.ToByte(TID_Length), DB, AccessPassWord);
                                    //MessageBox.Show(strEPC);
                                    //MessageBox.Show(res.ToString());
                                    if (resC == OK)
                                    {
                                        strTID = "";
                                        for (i = 0; i < Convert.ToByte(TID_Length) * 2; i++)
                                        {
                                            strtemp = DB[i].ToString("X2");
                                            strTID += strtemp;
                                        }
                                        if (!string.IsNullOrEmpty(strTID) && OnAfterReadCardInfo != null)
                                        {
                                            //MessageBox.Show(strEPC+":  "+strTID);
                                            
                                            OnAfterReadCardInfo(strTID, strEPC, nCurrnetAnt);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteLog(typeof(RFIDReader_747), ex);
                        }
                        finally
                        {
                            _isReading = false;
                        }
                        
                    }
                    
                }
                
            }
            
        }
        //根据卡号获取车号
        private string GetCarNo(string cardID)
        {
            string strCarNo = string.Empty;
            string strSQL = "select CHEHAO from RFID_READ where CARDID='" + cardID + "' and CARDSTATE='0'";
            DataTable dtRFID = DataAccess.ExecuteDataTable(strSQL);
            if (dtRFID != null && dtRFID.Rows.Count > 0)
            {
                strCarNo = dtRFID.Rows[0]["CHEHAO"].ToString().Trim();
            }
            return strCarNo;
        }
        /// <summary>
        /// 循环读卡时，轮流切换1号和2号天线
        /// </summary>
        /// <param name="ant"></param>
        /// <returns></returns>
        private int GetAntenna(int ant)
        {
            if (ant == InAnt)
                return OutAnt;
            else
                return InAnt;
        }

        private string GetHostIP()
        {
            IPAddress[] arrIPAddresses = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ips in arrIPAddresses)
            {
                if (ips.AddressFamily.Equals(AddressFamily.InterNetwork))
                {
                    return ips.ToString();
                }
            }
            return Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString();
        }

        // 改变界面按钮状态
        private void changeCtrlEnable(string state)
        {
            if (OnChangeCtrlEnable != null)
            {
                OnChangeCtrlEnable(state);
            }
        }
        // 改变闸机是否闭合的状态状态
        private void changeCloseState(string state)
        {
            if (IfCloseZhaji != null)
            {
                IfCloseZhaji(state);
            }
        }

        private void ShowMsg(string sMsg)
        {
            if (OnShowMsg != null)
            {
                OnShowMsg(sMsg);
            }
        }

        private void AfterUpBarrier()
        {
            if (OnAfterUpBarrier != null)
            {
                OnAfterUpBarrier();
            }
        }
    }
}
